package com.xinzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinzhi.mapper.LoanApplicationMapper;
import com.xinzhi.mapper.LoanInterestMapper;
import com.xinzhi.pojo.LoanApplication;
import com.xinzhi.pojo.LoanInterest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LoanApplicationService {

    @Autowired
    private LoanApplicationMapper loanApplicationMapper;

    @Autowired
    private LoanInterestMapper loanInterestMapper;

    /**
     * 根据id查找贷款申请
     * @return
     */
    public List<LoanApplication> getAllLoanApplications() {
        return loanApplicationMapper.selectList(null);
    }

    public LoanApplication getLoanApplicationById(Integer id) {
        return loanApplicationMapper.selectById(id);
    }

    /**
     * 创建新的贷款申请
     * @param loanApplication
     */
    public void createLoanApplication(LoanApplication loanApplication) {
        validateLoanApplication(loanApplication);
        loanApplicationMapper.insert(loanApplication);
    }

    /**
     * 更新贷款申请记录
     * @param loanApplication
     */
    public void updateLoanApplication(LoanApplication loanApplication) {
        validateLoanApplication(loanApplication);
        loanApplicationMapper.updateById(loanApplication);
    }

    public void deleteLoanApplication(Integer id) {
        loanApplicationMapper.deleteById(id);
    }

    /**
     * 查找贷款申请
     * @param applicationNumber
     * @return
     */
    public LoanApplication getLoanApplicationByApplicationNumber(String applicationNumber) {
        return loanApplicationMapper.selectOne(
                new QueryWrapper<LoanApplication>().eq("Dk_sqh", applicationNumber));
    }

    /**
     * 批准贷款申请然后更新状态
     * @param id
     * @param approvalDate
     * @param approverId
     */
    public void approveLoanApplication(Integer id, Date approvalDate, Integer approverId) {
        LoanApplication loanApplication = loanApplicationMapper.getLoanApplicationById(id);
        if (loanApplication != null) {
            loanApplication.setApplicationDate(approvalDate);
            loanApplication.setApproverId(approverId);
            loanApplicationMapper.updateLoanApplication(id, approvalDate, approverId, loanApplication.getLoanFlag());
        }
    }

    /**
     * 贷款的审批转账1或者0
     * @param id
     * @param approved
     */
    public void setLoanApprovalFlag(Integer id, boolean approved) {
        LoanApplication loanApplication = loanApplicationMapper.getLoanApplicationById(id);
        if (loanApplication != null) {
            loanApplication.setLoanFlag(approved ? 1 : 0);
            loanApplicationMapper.updateLoanApplication(id, null, null, loanApplication.getLoanFlag());
        }
    }

    /**
     * 贷款的审批流程
     * @param applicationId
     * @param approvalDate
     * @param approverId
     */
    public void approveLoan(Integer applicationId, Date approvalDate, Integer approverId) {
        approveLoanApplication(applicationId, approvalDate, approverId);
        setLoanApprovalFlag(applicationId, true);

        LoanApplication loanApplication = loanApplicationMapper.getLoanApplicationById(applicationId);
        if (loanApplication != null) {
            LoanInterest loanInterest = new LoanInterest();
            loanInterest.setLoanAccount(loanApplication.getLoanAccount());
            loanInterest.setLoanBalance(loanApplication.getLoanAmount());
            loanInterest.setInterestStartDate(approvalDate);
            loanInterest.setInterestDueDate(loanApplication.getApprovalDate());
            loanInterest.setInterestRate(0.05f);

            BigDecimal interestAmount = calculateInterest(loanInterest);
            loanInterest.setInterestAmount(interestAmount);

            loanInterestMapper.insert(loanInterest);
        }
    }

    /**
     * controller中的方法判断
     * @param loanApplication
     */
    private void validateLoanApplication(LoanApplication loanApplication) {
        if (loanApplication.getApplicationNumber() == null || !loanApplication.getApplicationNumber().matches("^[A-Za-z0-9]+$")) {
            throw new IllegalArgumentException("贷款号只能包含字母和数字");
        }
        if (loanApplication.getUserId() == null || loanApplication.getUserId() < 1) {
            throw new IllegalArgumentException("用户ID必须大于0");
        }
        if (loanApplication.getLoanType() == null || loanApplication.getLoanType().isEmpty()) {
            throw new IllegalArgumentException("贷款类型不能为空");
        }
        if (loanApplication.getLoanScope() == null || loanApplication.getLoanScope().isEmpty()) {
            throw new IllegalArgumentException("贷款范围不能为空");
        }
        if (loanApplication.getLoanAmount() == null || loanApplication.getLoanAmount().compareTo(BigDecimal.valueOf(0.01)) < 0) {
            throw new IllegalArgumentException("贷款金额必须大于0");
        }
        if (loanApplication.getRepaymentMethod() == null || loanApplication.getRepaymentMethod().isEmpty()) {
            throw new IllegalArgumentException("还款方式不能为空");
        }
        if (loanApplication.getMonthlyRepayment() == null || loanApplication.getMonthlyRepayment().compareTo(BigDecimal.valueOf(0.01)) < 0) {
            throw new IllegalArgumentException("月还款金额必须大于0");
        }
        if (loanApplication.getInvestigatorId() == null || loanApplication.getInvestigatorId().isEmpty()) {
            throw new IllegalArgumentException("信用调查员不能为空");
        }
    }

    /**
     * 计算利率使用精度高的类型
     * @param loanInterest
     * @return
     */
    private BigDecimal calculateInterest(LoanInterest loanInterest) {
        BigDecimal interest = loanInterest.getLoanBalance().multiply(BigDecimal.valueOf(loanInterest.getInterestRate()));
        return interest;
    }
}
